<template>
  <div class="container">
    <div class="footer_container">
      <audio
        :src="musicUrl"
        ref="audioPlayer"
        autoplay
        @play="changeState(true)"
        @pause="changeState(false)"
        @timeupdate="timeupdate"
        preload="auto"
      ></audio>
      <!-- 左边 -->
      <div class="left">
        <div class="avatar" @click="showLyric">
          <img :src="musicDetail.al.picUrl" v-if="musicDetail.al" />
          <img src="../../assets/test.jpg" v-else />
        </div>
        <div class="musicinfo" v-if="musicDetail.ar">
          <div class="musicName">
            {{ musicDetail.name }}
          </div>
          <div class="singerName">{{ musicDetail.ar[0].name }}</div>
        </div>
      </div>
      <!-- 中间 -->
      <div class="center">
        <div class="buttons">
          <span
            @click="
              playType =
                playType == 'order'
                  ? playType == 'round'
                  : playType == 'random'
                  ? 'round'
                  : 'random'
            "
          >
            <i class="iconfont icon-inturn" v-if="playType == 'order'"></i>
            <i
              class="iconfont icon-suijibofang"
              v-else-if="playType == 'random'"
            ></i>
            <i
              class="iconfont icon-bofang-xunhuanbofang"
              v-else-if="playType == 'round'"
            ></i>
          </span>
          <span>
            <i
              class="iconfont icon-shangyishou"
              @click="changeMusic('pre')"
            ></i>
          </span>
          <span @click="musicList.length != 0 ? changePlayState() : ''">
            <i
              class="iconfont icon-bofang"
              v-if="!this.$store.state.isPlay"
            ></i>
            <i class="iconfont icon-zanting" v-else></i>
          </span>
          <span>
            <i class="iconfont icon-xiayishou" @click="changeMusic('next')"></i>
          </span>
          <span>
            <i class="iconfont icon-aixin"></i>
          </span>
        </div>
        <div class="progressBar">
          <span class="currentTime">{{ currentTime | handleMusicTime }}</span>
          <div @mousedown="isChange = true" @mouseup="isChange = false">
            <el-slider
              v-model="timeProgress"
              class="progressSlider"
              :show-tooltip="false"
              @change="changeProgress"
            ></el-slider>
          </div>
          <span class="totalTime">{{ duration }}</span>
        </div>
      </div>
      <!-- 右边 -->
      <div class="right"></div>
    </div>
  </div>
</template>

<script>
import { handleMusicTime, handleSecond } from "../../filters";
let durationNum = 0;
export default {
  name: "BottomControl",
  data() {
    return {
      musicDetail: {},
      musicUrl: "",
      musicList: [],
      // 当前播放歌曲的背景图片
      authorImg: "",
      // 当前播放音乐的索引
      currentMusicIndex: 0,
      // 播放模式
      // 循环播放：round
      // 顺序播放：order
      // 随机播放：random
      playType: "random",
      // 音乐总时长
      duration: "00:00",
      // 当前播放时间位置
      currentTime: 0,
      // 进度条的位置
      timeProgress: 0,
      isChange: false,
    };
  },
  methods: {
    // 获取歌曲的url
    async getMusicDetail(id) {
      // console.log(id);
      const { data: res } = await this.$http("song/url", {
        params: { id: id },
      });
      // this.musicDetail = res;
      // console.log(this.musicDetail);
      // console.log(res);
      if (res.data[0].url == null) {
        this.$message.error("该歌曲暂无版权，将为您播放下一首");
        return;
      }
      this.musicUrl = res.data[0].url;
      this.$store.commit("updateMusicLoadState", false);
    },
    // 播放音乐的函数
    playMusic() {
      this.$refs.audioPlayer.play();
    },
    // 暂停播放的函数
    pauseMusic() {
      this.$refs.audioPlayer.pause();
    },
    // 点击播放键回调
    changePlayState() {
      this.$store.state.isPlay ? this.pauseMusic() : this.playMusic();
    },
    // audio开始或暂停播放的回调  在vuex中改变状态
    changeState(state) {
      this.$store.commit("changePlayState", state);
    },
    // 根据id找到musicList中对应的musicDetail
    getMusicDetailFromMusicList() {
      // console.log(this.musicList);
      let index = this.musicList.findIndex(
        (item) => item.id == this.$store.state.musicId
      );
      if (index !== -1) {
        // 记录当前音乐的index
        this.currentIndex = index;
        // 将索引传至vuex
        this.$store.commit("updateCurrentIndex", index);
        this.musicDetail = this.musicList[index];
        if (typeof this.musicDetail.dt === "number") {
          this.musicDetail.dt = handleMusicTime(this.musicDetail.dt);
        }
        this.duration = this.musicDetail.dt;
      }
    },
    // 切歌函数
    changeMusic(type) {
      if (type == "pre") {
        let currentMusicIndex = this.currentMusicIndex;
        let preIndex;
        if (this.playType == "order") {
          preIndex =
            currentMusicIndex - 1 < this.musicList.length - 1
              ? 0
              : currentMusicIndex - 1;
        } else if (this.playType == "random") {
          if (this.musicList.length == 1) {
            preIndex = currentMusicIndex;
          } else {
            preIndex = currentMusicIndex;
            while (preIndex == currentMusicIndex) {
              preIndex = Math.floor(Math.random() * this.musicList.length);
            }
          }
        } else if (this.playType == "round") {
          preIndex = currentMusicIndex;
        }
        console.log(this.musicList[preIndex].id);
        this.$store.commit("updateMusicId", this.musicList[preIndex].id);
      } else if (type == "next") {
        let currentMusicIndex = this.currentMusicIndex;
        let nextIndex;
        if (this.playType == "order") {
          nextIndex =
            currentMusicIndex + 1 == this.musicList.length
              ? 0
              : currentMusicIndex + 1;
        } else if (this.playType == "random") {
          if (this.musicList.length == 1) {
            nextIndex = currentMusicIndex;
          } else {
            nextIndex = currentMusicIndex;
            while (nextIndex == currentMusicIndex) {
              nextIndex = Math.floor(Math.random() * this.musicList.length);
            }
          }
        } else if (this.playType == "round") {
          nextIndex = currentMusicIndex;
        }
        console.log(this.musicList[nextIndex].id);
        this.$store.commit("updateMusicId", this.musicList[nextIndex].id);
      }
    },
    // 当前播放位置
    timeupdate() {
      // 当isChange为false时才触发
      if (!this.isChange) {
        // 拿到当前播放的位置
        let time = this.$refs.audioPlayer.currentTime;
        this.$store.commit("updateCurrentTime", time);
        time = Math.floor(time);
        if (time != this.duration) {
          this.currentTime = time * 1000;
          durationNum = handleSecond(this.duration);
          this.timeProgress = Math.floor(((time * 1000) / durationNum) * 100);
        }
      }
    },
    // 拖动滚动条事件
    changeProgress(e) {
      // 修改当前播放时间
      if (isNaN(durationNum)) return;
      this.currentTime = handleMusicTime(Math.floor((e / 100) * durationNum));
      // 改变audio的实际当前播放时间
      // this.$refs.audioPlayer.currentTime = this.currentTime;
      // this.playMusic();
      this.isChange = false;
    },
    // 打开歌词界面
    showLyric() {
      this.$store.commit("updateIsLyric");
    },
  },
  watch: {
    // 监听vuex中musicId的变化
    "$store.state.musicId"(id) {
      console.log("vuex中的id发生了变化");
      // 先暂停播放的音乐
      this.pauseMusic();
      this.musicList = this.$store.state.musicList;
      this.getMusicDetailFromMusicList();
      this.getMusicDetail(id);
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  border-top: 1px solid #ddd;
  width: 100%;
  height: 70px;
  position: fixed;
  bottom: 0;
  left: 0;
  // padding: 6px 10px;
  z-index: 10000;
  margin-top: 100px;
  background-color: #fff;
}
.footer_container {
  display: flex;
  width: 100%;
  justify-content: space-between;
  padding: 6px 10px;
}
.left {
  display: flex;
  align-items: center;
  width: 123px;
  .avatar {
    img {
      width: 50px;
      height: 50px;
      border-radius: 5px;
      overflow: hidden;
      margin-right: 10px;
      cursor: pointer;
    }
  }

  .musicinfo {
    display: flex;
    flex-direction: column;
    font-size: 12px;
    height: 50px;
    justify-content: space-around;
    color: rgb(37, 37, 37);
    cursor: pointer;

    .musicName {
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  .center {
    width: 600px;
    margin-top: 5px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;
  }
  .buttons {
    display: flex;
    align-items: center;
    height: 30px;
  }
}
.buttons span {
  width: 50px;
  height: 30px;
  padding: 20px;
  i {
    font-size: 30px;
  }
}
.progressBar {
  width: 100%;
  display: flex;
  height: 35px;
  justify-content: space-around;
  align-items: center;
  color: #aaaaaa;
  font-size: 13px;
}
.progressSlider {
  width: 300px;
}
</style>